var form = layui.form, layer = layui.layer, laydate = layui.laydate, upload = layui.upload, table = layui.table, $ = layui.jquery, id = getQueryVariable("id"),claimdetailcheckStatus=[];

lay('.starttime').each(function(){
    laydate.render({
        elem: this
    });
});

$('#editor-form').find('input,textarea,select').attr('disabled',true);
//表单初始值
if (id != "") {
    form.val("editor-form", {
        "receiptnumber": "初始值",
    })
}

//附件
let annexList = [];
//明细数据
let detailList = [];
//操作日志数据
let operationLog = [];
layer.ready(function () {

    //获取详情信息
    $.ajax({
        url:"receivePayment/detail?id="+id +"&type=2",
        success:function(res){
            if(res.status == 200){
                //主表信息赋值
                let vo =  res.data;
                form.val("editor-form", {
                    "billNo" : vo.billNo,
                    "time" : vo.time,
                    "customerName" : vo.customerName,
                    "accountName" : vo.accountName,
                    "currency" : vo.currency,
                    "rmbRate" : vo.rmbRate,
                    "usdRate" : vo.usdRate,
                    "entryAmount" : vo.entryAmount,
                    "bankDeductionExcept" : vo.bankDeductionExcept,
                    "bankDeductionCapital" : vo.bankDeductionCapital,
                    "collectionAmount" : vo.collectionAmount,
                    "claimed" : vo.claimed,
                    "toBeClaimed" : vo.toBeClaimed,
                    "salesman" : vo.salesman,
                    "departmentName" : vo.departmentName,
                    "voucherCompanyName" : vo.voucherCompanyName,
                    "operator" : vo.operator,
                    "memo" : vo.memo
                });

                //明细数据信息
                if(null != vo.detailList && vo.detailList.length > 0){
                    let tempDetailList = vo.detailList;
                    for(let i in tempDetailList){
                        if(1 == tempDetailList[i].confirmed){
                            tempDetailList[i]["LAY_CHECKED"] = "true";
                        }
                        detailList.push(tempDetailList[i]);
                    }
                }

                //附件信息信息
                if(null != vo.annexList && vo.annexList.length > 0){
                    annexList = vo.annexList;
                }

                //日志
                if(!isEmpty(res.data.logList) && res.data.logList.length > 0){
                    operationLog = res.data.logList;
                }

                table.reload('claimdetailtableid',{data : detailList});
                table.reload('attachmenttableid',{data : annexList});
                table.reload('logtableid',{data:operationLog});
                return false;
            }else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });
    form.render();

});
//--认领明细
    table.render({
        elem: '#claimdetail',
        id: 'claimdetailtableid',
        data: detailList,
        toolbar: '#claimdetailtoolbar',
        totalRow: true,
        cols: [[
            {checkbox: true},
            {field: 'numbers',width: 50,type:'numbers',title:'序号', totalRowText: '合计'},
            {field: 'invoiceNumber', width: 120, title: '发票编号',sort:true},
            {field: 'contractNo', width: 120, title: '合同编号',sort:true},
            {field: 'typeName', width: 120, title: '收款类型',sort:true},
            {field: 'collectionAmount', width: 120, title: '收汇金额',sort:true, totalRow: true},
            {field: 'foreignBankDeductions', width: 120, title: '国外银行扣费',sort:true, totalRow: true},
            {field: 'domesticBankCharge', width: 120, title: '国内银行扣费',sort:true, totalRow: true},
            {field: 'amountClaimed', width: 120, title: '认领金额',sort:true, totalRow: true},
            {field: 'allocatedAmount', width: 120, title: '已分摊金额',sort:true, totalRow: true},
            {field: 'unallocatedAmount', width: 120, title: '未分摊金额',sort:true, totalRow: true},
            {field: 'totalContract', width: 120, title: '合同总额',sort:true, totalRow: true},
            {field: 'totalInvoice', width: 120, title: '发票总额',sort:true, totalRow: true},
            {field: 'contractUnclaimedAmount', width: 150, title: '索赔金额', sort:true, totalRow: true},
            {field: 'refundAmount', width: 120, title: '退款金额', sort:true, totalRow: true},
            {field: 'claimDate', width: 120, title: '认领日期', sort:true, totalRow: true},
            {field: 'claimCustomer', width: 120, title: '认领客户', sort:true},
            {field: 'claimSalesman', width: 120, title: '认领业务员', sort:true},
            {field: 'memo', width: 120, title: '备注', sort:true}
        ]],
        page: true,
        height: 380
    });

//监听提交
form.on('submit(form-element)', function (data) {
    //获取选中的数据
    let checkStatus = table.checkStatus('claimdetailtableid');
    let checkStatusDataList = checkStatus.data;
    //获取选中的明细id,多个id以英文逗号隔开
    let ids = "";
    if(checkStatusDataList.length > 0) {
        for (let i in checkStatusDataList) {
            if (ids.length == 0) {
                ids = checkStatusDataList[i].id;
            } else {
                ids = ids + "," + checkStatusDataList[i].id;
            }
        }
    }
    //发送请求
    $.ajax({
        url:"receivePayment/addConfirmedStatus?ids=" + ids + "&id=" + id,
        success:function(res){
            if(res.status == 200){
                layer.msg("确认成功", {icon: 6});
                parent.table.reload('maininformationtableid');
                setTimeout(function () {
                    let index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);
                },500);
                return false;
            }else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });
});
//---附件
table.render({
    elem: '#attachment'
    , data: annexList
    , toolbar: '#attachmenttoolbar'
    , cols: [[
        {field: 'fileName', event:'fileName', title: '文件名', fixed: true}
        , {field: 'uploadTime', title: '上传日期', fixed: true}
        , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
    ]]
    , id: 'attachmenttableid'
    , height: 380
    , page: true
    , done: function (res, index, upload) {
        let data = res.data;
        for(let i in data){
            let flag = true;
            for(let j in annexList){
                if(data[i].id == annexList[j].id){
                    flag = false;
                    break;
                }
            }
            if(flag){
                annexList.push(data[i]);
            }
        }
    }
});
upload.render({
    elem: '#uploadfile'
    , url: 'transfer/uploadFile'
    , field: "uploadify"
    , accept: 'file'
    , multiple: true
    , auto: false
    , bindAction: '#testListAction'
    , choose: function (obj) {
        var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
        //读取本地文件
        obj.preview(function (index, file, result) {
            var tr = $(['<tr id="upload-' + index + '">'
                , '<td>' + file.name + '</td>'
                , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                , '<td>等待上传</td>'
                , '<td>'
                , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                , '</td>'
                , '</tr>'].join(''));

            //单个重传
            tr.find('.demo-reload').on('click', function () {
                obj.upload(index, file);
            });

            //删除
            tr.find('.demo-delete').on('click', function () {
                delete files[index]; //删除对应的文件
                tr.remove();
                uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
            });

            $("#uploadlist").append(tr);
        });
    }
    , parseData: function(res){
        return {
            "code": res.status,
            "count": res.total,
            "data": res.data
        };
    }
    , done: function (res, index, upload) {
        let data = res.data;
        for(var i in data){
            if (data[i].status) { //上传成功
                annexList.push(data[i]);
                var tr = $("#uploadlist").find('tr#upload-' + index)
                    , tds = tr.children();
                tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                tds.eq(3).html(''); //清空操作
                return delete this.files[index]; //删除文件队列已经上传成功的文件
            }
            this.error(index, upload);
        }
    }
    , error: function (index, upload) {
        var tr = $("#uploadlist").find('tr#upload-' + index)
            , tds = tr.children();
        tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
        tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
    }
});

table.on('toolbar(attachmenttable)', function (obj) {
    switch (obj.event) {
        case 'uploadfile':
            $("#uploadlist").html(""); //清空上传列表数据
            layer.open({
                type: 1,
                title: "文件上传",
                area: ['710px', '340px'],
                content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                , cancel: function (index, layero) {
                    table.reload('attachmenttableid', {data:annexList}); //点击关闭刷新表格
                }
            });
            break;
    }
    ;
});
table.on('tool(attachmenttable)', function (obj) {
    let data = obj.data;
    if (obj.event === 'download') { //下载
        let xmlHttpRequest = new XMLHttpRequest();
        let url = "wjinfo/downloadfile2?filename=" + data.filePath;
        xmlHttpRequest.open('GET', url, true);
        //设置请求头
        xmlHttpRequest.setRequestHeader("Content-type", "application/json")
        xmlHttpRequest.responseType = "blob";
        xmlHttpRequest.send(null);

        xmlHttpRequest.onload = function() {
            let content = xmlHttpRequest.response;
            // 组装a标签
            let elink = document.createElement("a");

            //设置文件下载路径
            elink.download = decodeURIComponent(data.fileName);
            elink.style.display = "none";
            let blob = new Blob([content], { type: 'application/force-download' });

            //解决下载不存在文件的问题，根据blob大小判断
            if(blob.size==0){
                layer.msg('服务器没找到此文件，请联系管理员!');
            }else{
                elink.href = window.URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                document.body.removeChild(elink);
            }

        }
    } else if (obj.event === 'del') {
        layer.confirm('确认删除?',
            confirmInfo(3,5), function (index) {
                obj.del();
                let id = data.id;
                for (var i = 0; i < annexList.length; i++) {
                    if (annexList[i].id == id) {
                        annexList.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                        i--; // 如果不减，将漏掉一个元素
                        break;
                    }
                }
                layer.msg("删除成功", {icon: 6});
                layer.close(index);
                table.reload('attachmenttableid', {data:annexList}); //ajax删除成功之后刷新表格
            });
    }else if (obj.event === 'fileName'){
        onLineFile(data.filePath);
    }
});

//---操作日志
let logData = [];
    table.render({
        elem: '#otherwarehouselog'
        , data: logData
        , cols: [[
              {field: 'operationType', title: '操作类型', fixed: true}
            , {field: 'operationName', title: '操作员'}
            , {field: 'operationTime', title: '操作日期'}
            , {field: 'operationContent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        , limit: 30//显示的数量
        , page: true
    });

$("#shutdown").on("click",function () {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
});

//提示信息渲染
function confirmInfo(icon, anim) {
    let data = {
        icon: icon,
        title: "提示",
        offset: "auto",
        skin: 'layui-layer-molv',
        anim: anim
    }
    return data;
}

//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}